package model.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import model.bean.Ambiente;
import model.bean.Dispositivo;
import model.factory.HibernateUtil;
import model.interfaces.IAmbiente;

public class AmbienteDAO implements IAmbiente {
	
	private Session session;
	
	@Override
	public void cadastrarAmbiente(Ambiente ambiente) {
		try{
			 session = HibernateUtil.getSession();
		     Transaction tx = session.beginTransaction();
		     session.saveOrUpdate(ambiente);
		     tx.commit();
			}catch(Exception e){
				e.printStackTrace();
			}
	}

	@Override
	public void removeAmbienteByNome(String nomeAmbiente) {
		session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		String hql = " DELETE FROM Ambiente a WHERE a.nome LIKE :nomeAmbiente ";
		Query q = session.createQuery(hql);
		q.setString("nomeAmbiente", nomeAmbiente);
		q.executeUpdate();
		tx.commit();
		
	}

	@Override
	public void removeAmbienteById(int idAmbiente) {
		session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		String hql = " DELETE FROM Ambiente a WHERE a.ambienteId = :idAmbiente ";
		Query q = session.createQuery(hql);
		q.setInteger("idAmbiente", idAmbiente);
		q.executeUpdate();
		tx.commit();
		
	}

	@Override
	public Ambiente findAmbienteById(int idAmbiente) {
		session = HibernateUtil.getSession();
		Query q = session.createQuery("FROM Ambiente a WHERE a.ambienteId = :idAmbiente");
		q.setInteger("idAmbiente", idAmbiente);
		return (Ambiente) q.uniqueResult(); 
	}
	
	
	@Override
	public void vinculaAmbienteEventoPeloNome(String nomeEvento , String nomeAmbiente) {
		session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		String sql = " INSERT INTO evento_ambiente VALUES ( "
				+ " (SELECT DISTINCT e.id_evento FROM evento e WHERE e.nome LIKE :nomeEvento) , "
				+ " (SELECT DISTINCT amb.id_ambiente FROM ambiente amb WHERE amb.nome LIKE :nomeAmbiente ) "
				+ " )";
		Query q = session.createSQLQuery(sql);// .setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
		q.setString("nomeEvento", nomeEvento);
		q.setString("nomeAmbiente", nomeAmbiente);
		q.executeUpdate();
		tx.commit();

	}

	
	
	
}	
	